package tec.code;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

public class Display {
	public static void main(String[] args) throws Exception {
		Display chk = new Display();
		//chk.count();
		chk.countDiff();
		chk.saveDiff();
		//chk.countNonGBK();
	}
	
	private Display() throws IOException {
		tsMap = new HashMap<Character, Character>();
		stMap = new HashMap<Character, Character>();
		load();
	}
	
	private void load() throws IOException {
		LineIterator content = FileUtils.lineIterator(new File("cfg/TS.ini"), "UTF-8");
		while(content.hasNext()) {
			String line = content.next();
			tsMap.put(getTrandition(line), getSimple(line));
			stMap.put(getSimple(line), getTrandition(line));
		}
	}
	
	public void count() {
		System.out.println("Number of Characters: " + tsMap.size());
	}
	
	public void countDiff() {
		System.out.println("Number of Difference: " + diffChar().size());
	}
	
	public void countNonGBK() throws UnsupportedEncodingException {
		int nNonGBK = 0;
		for(char sc : stMap.keySet()) {
			char gbk = toGBK(sc);
			if(gbk <= 0xB0A0 || gbk >= 0xF7FF) {
				System.out.println(FormatUtil.formatByte(ConvertUtil.toByte(gbk)));
				nNonGBK++;
			}
		}
		System.out.println("Number of Non GBK: " + nNonGBK);
	}
	
	public void saveDiff() throws IOException {
		Set<Character> diff = diffChar();
		Writer out = new OutputStreamWriter(new FileOutputStream("txt/diff.txt"), "GB2312");
		for(char c : diff) out.write(c);
		out.flush();
		out.close();
	}
	
	private Set<Character> diffChar() {
		Set<Character> simple = stMap.keySet();
		Set<Character> diff = new HashSet<Character>();
		for(char sc : simple) {
			char tc = stMap.get(sc);
			if(sc != tc) diff.add(sc);
		}
		return(diff);
	}
	
	private static char getSimple(String line) {
		return((line.split("\\s+")[0]).toCharArray()[0]);		
	}
	
	private static char getTrandition(String line) {
		return((line.split("\\s+")[1]).toCharArray()[0]);				
	}
	
	private static char toGBK(char c) throws UnsupportedEncodingException {
		char gbk = 0;
		String s = new String(new char[] {c});
		byte[] bs = s.getBytes("GB2312");
		gbk = (char) bs[0];
		gbk = (char) (gbk << 8);
		if(bs.length > 1) gbk = (char) (gbk + bs[1]);
		return(gbk);
	}
	
	private Map<Character, Character> tsMap, stMap;
}
